import { baseUrl } from './env'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

const specialHeaders = ['/user/user_corp_list', '/user/select_corp']
const printRequests = [  //打印相关接口，需要在header中加CORP-ID
	'/lianke_print/bind_devices',
	'/lianke_print/remove_devices',
	'/lianke_print/get_all_devices',
	'/lianke_print/printer_list',
	'/lianke_print/add_job',
	'/lianke_print/job_result',
	'/pdf_files/convert_pdf',
	'/upload_file/ali_oss_priv'
]

export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
	type = type.toUpperCase();  //转大写
	let request_url = baseUrl + url;

	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			if (data[key]) {
				dataStr += key + '=' + data[key] + '&';
			}
		})

		if (dataStr !== '') {
			dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'));
			request_url = request_url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {
		let requestConfig = {
			credentials: 'include',
			method: type,
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			mode: "cors",
			cache: "no-cache"
		}

		if (type=='POST' || type=='PUT' || type=='DELETE') {
			Object.defineProperty(requestConfig, 'body', {
				value: JSON.stringify(data)
			})
		}

		if (specialHeaders.includes(url)){
			requestConfig.headers['User-Login-Token'] = getToken() || ''
		}else{
			requestConfig.headers['TOKEN'] = getToken() || ''
		}

		if (printRequests.includes(url)){
			requestConfig.headers['CORP-ID'] = data.corp || data.corpId || data.corp_id
		}
		
		try {
			const response = await fetch(request_url, requestConfig);
			const responseJson = await response.json();
			let code = responseJson.code
			if (code == 200 || code == 997 || code == 0){
				return responseJson
			}else{
				Message({
					message: responseJson.data.msg || responseJson.msg,
					type: 'error'
				});
				return Promise.reject('error')
			}
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, request_url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object') {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}